﻿using System;
using System.Globalization;
using Windows.ApplicationModel.Core;
using Windows.Globalization;
using Windows.Storage;
using Windows.System.Threading;
using Windows.UI.Xaml;

namespace BuddyTracker.ViewModel.Helpers
{
    /// <summary>
    /// Helper class for loading, saving user settings and also home for background stuff.
    /// </summary>
    class SettingsHelper
    {
        /// <summary>
        /// Reference to MainViewModel.
        /// </summary>
        private MainViewModel context;
        /// <summary>
        /// If settings are being loaded, behaviour is different.
        /// </summary>
        private bool loadingSettings;

        public SettingsHelper(MainViewModel m) //constructor dependency injection
        {
            this.context = m;
        }

        /// <summary>
        /// Writes default values to local settings isolated storage.
        /// </summary>
        public void WriteDefaults()
        {

            var localSettings = ApplicationData.Current.LocalSettings;

            localSettings.Values["AutomaticPosting"] = 0;
            localSettings.Values["Encoder"] = 1;
            localSettings.Values["AutomaticPostingInterval"] = 0;
            localSettings.Values["BuddyTrackerRefreshInterval"] = 0;
            localSettings.Values["Language"] = 0;
            localSettings.Values["Key"] = string.Empty;

        }

        /// <summary>
        /// Loads setting from isolated storage and updates them to the MainViewModel, also starts background timers.
        /// </summary>
        public void LoadSettings()
        {
            var localSettings = ApplicationData.Current.LocalSettings;
            try
            {
                loadingSettings = true;
                context.SettingAutomaticPosting = (int)localSettings.Values["AutomaticPosting"];
                context.SettingEncoder = (int)localSettings.Values["Encoder"];
                context.SettingAutomaticPostingInterval = (int)localSettings.Values["AutomaticPostingInterval"];
                context.SettingBuddyTrackerInterval = (int)localSettings.Values["BuddyTrackerRefreshInterval"];
                context.SettingLanguage = (int)localSettings.Values["Language"];
                context.KeyPhraseText = (string) localSettings.Values["Key"];
                loadingSettings = false;

                //gonna start background threads
                StartTimers();

            }
            catch
            {
                WriteDefaults();                
            }
        }

        /// <summary>
        /// Changes culture of the application pernamently;
        /// </summary>
        /// <param name="CultureName"></param>
        public void SetLanguage(string CultureName)
        {
            var culture = new CultureInfo(CultureName);
            ApplicationLanguages.PrimaryLanguageOverride = culture.Name;
            CultureInfo.DefaultThreadCurrentCulture = culture;
            CultureInfo.DefaultThreadCurrentUICulture = culture;
        }

        /// <summary>
        /// Saves settings from MainViewModel to Isolated storage, and starts background timers.
        /// </summary>
        public void SaveSettings()
        {
            if (loadingSettings) //ignore calls until done
                return;
            var localSettings = ApplicationData.Current.LocalSettings;

            localSettings.Values["AutomaticPosting"] = context.SettingAutomaticPosting;
            localSettings.Values["Encoder"] = context.SettingEncoder;
            localSettings.Values["AutomaticPostingInterval"] = context.SettingAutomaticPostingInterval;
            localSettings.Values["BuddyTrackerRefreshInterval"] = context.SettingBuddyTrackerInterval;
            localSettings.Values["Language"] = context.SettingLanguage;
            localSettings.Values["Key"] = context.KeyPhraseText;

            //settings changed, starting background workers
            StartTimers();

        }

        #region Timers

        /// <summary>
        /// Timer for automatically posting user's current location.
        /// </summary>
        private ThreadPoolTimer automaticPostingTimer;
        /// <summary>
        /// Timer for automatically updating friends locations, and user location.
        /// </summary>
        private ThreadPoolTimer buddyTrackerRefreshTimer;

        /// <summary>
        /// Stops the timers and destroys them if they are running.
        /// </summary>
        public void TryStopTimers()
        {
            if (automaticPostingTimer != null)
            {
                automaticPostingTimer.Cancel();
                automaticPostingTimer = null;
            }

            if (buddyTrackerRefreshTimer != null)
            {
                buddyTrackerRefreshTimer.Cancel();
                buddyTrackerRefreshTimer = null;
            }
        }

        /// <summary>
        /// Starts the background timers immediatelly.
        /// </summary>
        private void StartTimers()
        {
            TryStopTimers(); // are they already running? User changed settings.

            var localSettings = ApplicationData.Current.LocalSettings;

            //automatic posting
            
            if ((int)localSettings.Values["AutomaticPosting"] == 1)
            {

                var value = (int)localSettings.Values["AutomaticPostingInterval"];

                int minutes = 5;

                if (value == 1)
                    minutes = 15;
                else if (value == 2)
                    minutes = 30;

                TimeSpan period = TimeSpan.FromMinutes(minutes);

                automaticPostingTimer = ThreadPoolTimer.CreatePeriodicTimer(async (source) =>
                {
                    var dispatcher = CoreApplication.MainView.CoreWindow.Dispatcher;

                    await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        context.PostLocation();
                    });
                }, period);

            }

            //buddy tracker refreshing

            if ((int)localSettings.Values["BuddyTrackerRefreshInterval"] >= 1)
            {

                var value = (int)localSettings.Values["AutomaticPostingInterval"];

                int seconds = 30;

                if (value == 2)
                    seconds = 300;
                else if (value == 3)
                    seconds = 900 ;

                TimeSpan period = TimeSpan.FromSeconds(seconds);

                buddyTrackerRefreshTimer = ThreadPoolTimer.CreatePeriodicTimer(async (source) =>
                {
                    var dispatcher = CoreApplication.MainView.CoreWindow.Dispatcher;

                    await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        context.Refresh();
                    });

                }, period);
            }
        #endregion
        }
    }
}
